package cn.yh.register.order.service.impl;

import cn.yh.register.client.HospitalFeignClient;
import cn.yh.register.common.exception.RegisterException;
import cn.yh.register.common.helper.HttpRequestHelper;
import cn.yh.register.common.result.ResultCodeEnum;
import cn.yh.register.enums.OrderStatusEnum;
import cn.yh.register.enums.PaymentStatusEnum;
import cn.yh.register.model.order.OrderInfo;
import cn.yh.register.model.order.PaymentInfo;
import cn.yh.register.order.mapper.PaymentInfoMapper;
import cn.yh.register.order.service.OrderService;
import cn.yh.register.order.service.PaymentService;
import cn.yh.register.vo.order.SignInfoVo;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class PaymentServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentService {
    @Autowired
    OrderService orderService;
    @Autowired
    HospitalFeignClient hospitalFeignClient;

    /**
     * 保存交易记录
     * @param orderInfo
     * @param paymentType 支付类型（1：支付宝 2：微信）
     */
    @Override
    public void savePaymentInfo(OrderInfo orderInfo, Integer paymentType) {
        // 先查询是否有该支付记录
        PaymentInfo paymentInfo = baseMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>()
                .eq(PaymentInfo::getOrderId, orderInfo.getId())
                .eq(PaymentInfo::getPaymentType, paymentType));
        if (paymentInfo == null) {
            // 保存支付记录
            paymentInfo = new PaymentInfo();
            paymentInfo.setCreateTime(new Date());
            paymentInfo.setOrderId(orderInfo.getId());
            paymentInfo.setPaymentType(paymentType);
            paymentInfo.setOutTradeNo(orderInfo.getOutTradeNo());
            //订单状态 1：支付中  2：已支付
            paymentInfo.setPaymentStatus(PaymentStatusEnum.UNPAID.getStatus());
            String subject = new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd")
                    +"|"+orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle();
            paymentInfo.setSubject(subject);
            paymentInfo.setTotalAmount(orderInfo.getAmount());
            baseMapper.insert(paymentInfo);
        }

    }

    /**
     * 支付成功 更新交易记录 更新订单状态 对接医院系统
     * @param outTradeNo  订单号
     * @param paymentType 支付类型（1：支付宝 2：微信）
     * @param paramMap    微信接口返回的数据
     */
    @Override
    public void paySuccess(String outTradeNo, Integer paymentType, Map<String, String> paramMap) {
        PaymentInfo paymentInfo = this.getPaymentInfo(outTradeNo, paymentType);
        if (paymentInfo == null) {
            throw new RegisterException(ResultCodeEnum.DATA_ERROR);
        }
        if (!paymentInfo.getPaymentStatus().equals(PaymentStatusEnum.UNPAID.getStatus())) {
            return;
        }
        // 更新交易记录
        paymentInfo.setPaymentStatus(PaymentStatusEnum.PAID.getStatus()); // 2：已支付
        paymentInfo.setTradeNo(paramMap.get("transaction_id")); // 微信交易流水号
        paymentInfo.setCallbackTime(new Date()); //
        paymentInfo.setCallbackContent(paramMap.toString());//微信相应的数据
        // this.updateById(paymentInfo);
        this.updatePaymentInfo(outTradeNo, paymentInfo);
        // 更新订单状态
        OrderInfo orderInfo = orderService.getOrderInfo(paymentInfo.getOrderId());
        orderInfo.setOrderStatus(OrderStatusEnum.PAID.getStatus());
        orderService.updateById(orderInfo);
        // 对接医院系统 更新状态
        // 获取签名信息
        SignInfoVo signInfoVo = hospitalFeignClient.getSignInfoVo(orderInfo.getHoscode());
        if (signInfoVo==null) {
            throw new RegisterException(ResultCodeEnum.DATA_ERROR);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("hoscode",orderInfo.getHoscode());
        map.put("hosRecordId",orderInfo.getHosRecordId());
        map.put("timestamp", HttpRequestHelper.getTimestamp());
        map.put("sign",HttpRequestHelper.getSign(map,signInfoVo.getSignKey()));
        JSONObject jsonObject = HttpRequestHelper.sendRequest(map, signInfoVo.getApiUrl() + "/order/updatePayStatus");
        if(jsonObject.getInteger("code") != 200) {
            throw new RegisterException(jsonObject.getString("message"), ResultCodeEnum.FAIL.getCode());
        }
    }

    /**
     * 查询交易记录
     * @param outTradeNo  订单号
     * @param paymentType 支付类型（1：支付宝 2：微信）
     * @return 交易记录
     */
    @Override
    public PaymentInfo getPaymentInfo(String outTradeNo, Integer paymentType) {
        return baseMapper.selectOne(new LambdaQueryWrapper<PaymentInfo>()
                .eq(PaymentInfo::getOutTradeNo, outTradeNo).eq(PaymentInfo::getPaymentType, paymentType));
    }

    /**
     * 修改订单状态
     * @param outTradeNo  订单号
     * @param paymentInfo 交易记录
     */
    @Override
    public void updatePaymentInfo(String outTradeNo, PaymentInfo paymentInfo) {
        baseMapper.update(paymentInfo,new LambdaQueryWrapper<PaymentInfo>()
                .eq(PaymentInfo::getOutTradeNo, outTradeNo));

    }
}
